<?php

use com\masfletes\db\DBUtil;

/**
 * El propósito del controlador es realizar operaciones CRUD con el modelo vehículos
 *
 * @author Andrés Hdz
 */
class OperationController_UsersController extends JController {

    private $userSessionId;

    /*
      public $p_id;
      public $p_name;
      public $p_type;
      public $p_volume;
      public $p_economic_number;
      public $p_capacity;
      public $p_status;
      public $p_trade_mark;
      public $p_plate;
      public $p_color;
      public $p_gps;
      public $p_model;
      public $p_width;
      public $p_height;
      public $p_deep;
     */

    public function init() {
        parent::init();
        if (!Model3_Auth::isAuth()) {
            $this->redirect('Index/index');
        }
        $this->userSessionId = $_SESSION['USERSESSIONID'];
    }

    public function indexAction() {
        //Solo el Index se devuelve de manera normal(text/html)
        $this->setResponseJSON(FALSE);
        
        //Includes específicos de esta página        
        $this->view->customScripts .= $this->view->getJsManager()->loadJsFile('application/OperationController/Users/usersApp.js', false, TRUE);
        $this->view->getJsManager()->addJsVarEncode('contextPath', $this->view->url(array(
                    'controller' => 'Users')));
        $this->view->setTemplate('GeneralContentLayout');
    }

    public function getUsersAction() {
        $params = $this->getRequest()->getPostJson();
        
        $page = $this->getArrayValue('page', $params);
        $limit = $this->getArrayValue('rowsPerPage', $params);
        $sidx = $this->getArrayValue('sortField', $params);
        $sord = $this->getArrayValue('sortDir', $params);
        $id = $this->getArrayValue('id', $params);
        $userType =  $this->getArrayValue('type', $params);
        
        if (!$sidx)
            $sidx = 1;

        try {
            $this->permitirAcceso($this->userSessionId, 'usuarios', 'listar');
            $conn = $this->getConnection();

            $parameters = array($this->userSessionId, $page, $limit, $sidx, $sord, $id, $userType);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_users_listar', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (PDOException $ex) {
            $errMsg = utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            }
            return;
        } catch (Exception $generalEx) {
            echo json_encode(array("error" => $generalEx->getMessage(), "code" => $generalEx->getCode(), "trace" => $generalEx->getTraceAsString()));
            return;
        }
        echo json_encode($resultsets);
    }

    public function saveAction() {
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);
        $category_id = $this->getArrayValue('category_id',$params);
	$parent_id =  $this->getArrayValue('parent_id', $params);
	$point_id = $this->getArrayValue('point_id', $params);
        $code = $this->getArrayValue('code', $params);
        $status = $this->getArrayValue('status', $params);
        $first_name = $this->getArrayValue('first_name', $params);
        $last_name = $this->getArrayValue('last_name', $params);
        $type = $this->getArrayValue('type', $params);        
	$username = $this->getArrayValue('username', $params);
	$password = $this->getArrayValue('password', $params);
	$title = $this->getArrayValue('title', $params);
	$commercial_name = $this->getArrayValue('commercial_name', $params);
	$cell_phone = $this->getArrayValue('cell_phone', $params);
	$local_number = $this->getArrayValue('local_number', $params);
	$type = $this->getArrayValue('type', $params);        
	$dayInvoice  = $this->getArrayValue('dayInvoice', $params);
        //Se establece el día de pago por defecto en 0
        $dayInvoice = 0;
        
            
        try {
            $this->permitirAcceso($this->userSessionId, 'usuarios', ($id==null) ? 'agregar' : 'editar');
            
            $conn = $this->getConnection();
            $parameters = array($id, $category_id, Model3_Auth::getCredentials("id"), $point_id, $code, $status, $first_name, $last_name, $username, $password
                    ,$title, $commercial_name, $cell_phone,$local_number, $type, $dayInvoice);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_users_guardar', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
     public function deleteAction() {
          $params = $this->getRequest()->getPostJson();
          $id = $params['id'];
          if($id==null)
                return;
          try {
            $this->permitirAcceso($this->userSessionId, 'usuarios', 'eliminar');
            
            $conn = $this->getConnection();
            $parameters = array($id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_users_borrar', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = /*utf8_encode(*/$ex->getMessage()/*)*/;
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    function getUserCatalogAction(){
        $params = $this->getRequest()->getPostJson();
        $userName = $this->getArrayValue('param1', $params);

        try {
            $this->permitirAcceso($this->userSessionId, 'vehiculos', 'listar');
            $conn = $this->getConnection();
            $parameters = array($this->userSessionId,$userName);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_userCatalog_list', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (PDOException $ex) {
            $errMsg = $ex->getMessage(); //utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            }
            return;
        } catch (Exception $generalEx) {
            echo json_encode(array("error" => $generalEx->getMessage(), "code" => $generalEx->getCode(), "trace" => $generalEx->getTraceAsString()));
            return;
        }
        echo json_encode($resultsets);
    }
}
